package com.shuyun.ccms.encrypt.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

public class ConnectionUtil {
	private Logger logger = LoggerFactory.getLogger(ConnectionUtil.class);
	private String tenantId;
	private static ConnectionUtil connUtil = null;

	public static ConnectionUtil newInstance(){
		if(connUtil == null){
			connUtil = new ConnectionUtil();
		}
		return connUtil;
	}

	private Map<String, String> readCMDB() throws IOException {
        HttpClient httpClient = new HttpClient();

        GetMethod getMethod = new GetMethod("http://api-ops.fenxibao.com/api/ccmsuser/");
        getMethod.addRequestHeader("Content-Type", "application/json");
        getMethod.addRequestHeader("Authorization", "Token acea12fe80e51f9b8db5cff70802020abefd9a41");
        getMethod.setQueryString("domain=" + tenantId);

        httpClient.executeMethod(getMethod);
        Map<String, ?> object = new Gson().fromJson(new InputStreamReader(getMethod.getResponseBodyAsStream()), Map.class);
        Double count = (Double) object.get("count");

        if (count != 1) {
        	logger.info(" get cmdb info failed. tenantId = " + tenantId);
        	throw new RuntimeException("get cmdb info failed");
        }

        List<Map<String, String>> results = (List<Map<String, String>>) object.get("results");
        return results.get(0);
    }

	public Connection getTenantConn(String tenantId){
		Connection conn = null;
		try {
			this.tenantId = tenantId;

//			Map<String, String> tenantMap = this.readCMDB();
			String host = "localhost";//tenantMap.get("db_host");
			String username = "root";//tenantMap.get("db_user");
			String password = "shuyun";//tenantMap.get("db_pass");
			String port = "3306";//tenantMap.get("db_port");
			String schema = "test_dynamic_01";//tenantMap.get("db_name");

			Class.forName("com.mysql.jdbc.Driver");
			//jdbc:mysql://dbi01.sho.shuyun.com/ccms6_lw?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
			String url = "jdbc:mysql://" + host +":" + port + "/" + schema + "?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true";
			//logger.info(" get tenant conn begin . url: " + url);
			conn = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			logger.error("create tenant connection failed. " + e.getMessage());
			e.printStackTrace();
			throw new RuntimeException("get cmdb conn failed" + e.getMessage());
		}
		logger.info(" get tenant conn end");
		return conn;
	}

	public void closeConn(Connection conn){
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void closeStatement(Statement st){
		if(st != null){
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	 }


	public void closePreparedStatement(PreparedStatement ps){
		if(ps != null){
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	 }

	public void closeResultSet(ResultSet rs){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void close(PreparedStatement ps,ResultSet rs){
		this.closePreparedStatement(ps);
		this.closeResultSet(rs);
	}




	public static void main(String[] args){
		/*String line = "    ����19890202";
		String[] strs = line.split(",");
		System.out.println(strs.length);
		for(String str : strs){
			System.out.println(str);
		}*/
		Connection conn = ConnectionUtil.newInstance().getTenantConn("qiushi6");
		System.out.println(conn);
	}

}
